#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#include <ctype.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/time.h>
#include <host.h>
#include <ants.h>
#include <http.h>
#include <ftp.h>
#include <config.h>
	
static struct mission *pms;
	
void exit_handle(int sig) {
	int i, thread;
	struct ants *ant;
	thread = pms->thread;
	if(pms->fd)
		state_save(pms);
	ant = pms->first_ant;
	if(ant == NULL)
		goto no_ants;
	for(i = 0; i < thread; i++) {
		if(ant[i].s) {
			close(ant[i].s);
			ant[i].s = 0;
		}
		if(ant[i].fd) {
			close(ant[i].fd);
			ant[i].fd = 0;
		}
		if((pms->port == 21) && (ant[i].s_c)) {
			close(ant[i].s_c); /*close ftp control socker*/
			ant[i].s_c = 0;
		}
	}	
	if(ant->buffer_start)
		free(ant->buffer_start);
	if(ant->data)
		free(ant->data);
no_ants:
	printf("---download exit---\n");
	exit(0);
}	
	
void init_sig(void) {
	struct sigaction act;
	act.sa_handler = exit_handle;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	if(sigaction(SIGINT, &act, NULL) < 0)
		fprintf(stderr, "Install Signal Action Error:%s\n\a", strerror(errno));
} 
	
int main() {
	int i, fd, thread;
	struct mission my_mission;
	pms = &my_mission;
	memset(pms, 0, sizeof(struct mission));
	char name[MAX_HOSTNAME];
	char referer[MAX_HOSTNAME];
	char path[MAX_HOSTNAME] = "/usr/src/";
	pms->file_path = path;
	thread = 5;
	init_sig();
	while(1) {
		fd = scan_temp(path);
		if(fd >= 1) {
			i = rebuild_ants(fd, pms);
			if(i) {
				download(pms);
			}
		}
		else {
			printf("please input url.\n");
			do {
				fgets(name, MAX_HOSTNAME, stdin);
				if(strlen(name) > 3)
					break;
				if(name[0] == 'q' || name[0] =='Q')
					exit(0);
			} while(1);
			name[strlen(name) - 1] = 0;
			if(strstr(name, "http")) {
				printf("please input referer.\n");
				scanf("%s", referer);
				if(strlen(referer) <= 3)
					*pms->referer = 0;	/*auto fill*/
				else
					strcpy(pms->referer, referer);
			}
			else if(strstr(name, "ftp")) {
				strcpy(pms->user, "anonymous");
				strcpy(pms->pass, "mozilla@example.com");
			}
			
			if(build_ants(pms, name, &thread))
				download(pms);
		}
	}
	exit(0);
	return 0;
}
